package huffmantree;

import java.util.ArrayList;
import java.util.Collections;

public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13, 7, 8, 3, 29, 6, 1};
        Node huffmanTree = createHuffmanTree(arr);
        preOrder(huffmanTree);

    }

    public static void preOrder(Node root) {
        if (root == null) {
            System.out.println("空数不能遍历");
        } else {
            root.preOrder();
        }

    }

    //创建赫夫曼数的方法
    public static Node createHuffmanTree(int[] arr) {
        ArrayList<Node> nodes = new ArrayList<>();
        for (int value :
                arr) {
            nodes.add(new Node(value));
        }

        while (nodes.size() > 1) {

            Collections.sort(nodes); //排序

            //取出最小
            Node left = nodes.get(0);
            //第二小
            Node right = nodes.get(1);

            Node parrnt = new Node(left.value + right.value);

            parrnt.left = left;
            parrnt.right = right;

            //删除已经用过的
            nodes.remove(left);
            nodes.remove(right);

            nodes.add(parrnt);

        }
        return nodes.get(0);
    }
}


//节点类
class Node implements Comparable<Node> {
    int value;//节点全脂
    Node left; //左
    Node right;//右

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    //前序遍历
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    @Override
    public int compareTo(Node o) {
        //从小到大排序
        return this.value - o.value;
    }
}